package com.fg.cloud.manager.service.agency.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.fg.cloud.common.PageUtils;
import com.fg.cloud.common.construction.Select;
import com.fg.cloud.common.construction.Tree;
import com.fg.cloud.common.validate.LongUtils;
import com.fg.cloud.manager.entry.BaseEntity;
import com.fg.cloud.manager.entry.agency.AgencyAreaEntity;
import com.fg.cloud.manager.entry.agency.vo.AgencyAreaVo;
import com.fg.cloud.manager.mapper.BaseMapper;
import com.fg.cloud.manager.mapper.agency.AgencyAreaMapper;
import com.fg.cloud.manager.service.BaseServiceImpl;
import com.fg.cloud.manager.service.agency.AgencyAreaService;

/**
 * 经销商-区域service实现
 * @author around
 * @date 2017-6-23
 */
@Service
public class AgencyAreaServiceImpl extends BaseServiceImpl implements AgencyAreaService {

	@Autowired
	private AgencyAreaMapper agencyAreaMapper;
	
	@Override
	protected <T extends BaseEntity> BaseMapper getBaseMapper() {
		return agencyAreaMapper;
	}
	
	@SuppressWarnings("unchecked")
	public <T extends BaseEntity> T find(long id) {
		return (T) agencyAreaMapper.selectByPrimaryKey(id);
	}
	
	@Override
	@Transactional
	public boolean updateByPrimaryKeySelective(AgencyAreaVo area) {
		//完善：追加处理级联更改区域，将指定区域集合放置到新的位置
		AgencyAreaEntity entity = agencyAreaMapper.selectByPrimaryKey(area.getId());
		//判断是否编码发生更改，若更改则级联更改
		if (!entity.getNumber().equals(area.getNumber())) {
			agencyAreaMapper.batchUpdateLowerArea(entity.getNumber(), 
					area.getNumber(), entity.getNumber()+"_"+entity.getId());
		}
		
		return agencyAreaMapper.updateByPrimaryKeySelective(area) > 0 ? true : false;
	}
	

	@Override
	public void findList(PageUtils<AgencyAreaEntity> pageinfo) {
		long total = agencyAreaMapper.filterCount(pageinfo.getCondition());
		pageinfo.setTotal(total);
		if(total > 0) {
			pageinfo.setData(agencyAreaMapper.findList(pageinfo));
		} else {
			pageinfo.setData(new ArrayList<AgencyAreaEntity>());
		}
	}
	
	@Override
	public long selectAgencyByArea(Long areaId) {
		return agencyAreaMapper.selectAgencyByArea(areaId);
	}
	
	@Override
	@Transactional
	public int delete(Long id) {
		//完善：追加厂商用户设置关联区域数据权限
		agencyAreaMapper.deleteUserArea(id);
		return agencyAreaMapper.deleteByPrimaryKey(id);
	}

	/**
	 * 瀑布式替代递归，变更查询封装效率
	 */
	@Override
	public List<AgencyAreaVo> findList(Long facId) {
		List<AgencyAreaVo> areaList = agencyAreaMapper.selectList(facId);
		AgencyAreaVo area = null;
		
		Map<Long, List<AgencyAreaVo>> map = new HashMap<Long, List<AgencyAreaVo>>();
		List<AgencyAreaVo> valueList = null;

		for (int i = 0; i < areaList.size(); i++) {
			area = areaList.get(i);
			/*System.out.println("区域为："+area);*/
			//从已有容器查找是否存在同级元素的集合
			if(map.get(area.getPid()) == null) valueList = new ArrayList<AgencyAreaVo>();
			else valueList = map.get(area.getPid());
			//根据当前节点查找下级节点集合是否存在，有则纳入封装体系
			if(map.get(area.getId()) != null)
				area.setChilds(map.get(area.getId()));
			
			valueList.add(area);
			map.put(area.getPid(), valueList);
		}
		
		return map.get(0L);
	}
	
	public List<Select> findListByFacId(Long facId){
		
		return agencyAreaMapper.findListByFacId(facId);
	}
	
	@Override
	@Transactional
	public boolean updateStatus(Long id, String number) {
		agencyAreaMapper.deleteUserArea(id);
		return agencyAreaMapper.updateStatus(id, number, -1) > 0 ? true : false;
	}
	
	/**
	 * 封装通用的树形结构
	 * @param area
	 * @return
	 */
	private Tree convert(AgencyAreaVo area) {
		Tree tree = new Tree();
		tree.setId(area.getId());
		tree.setNumber(area.getNumber());
		tree.setPid(area.getPid());
		tree.setLabel(area.getName());
		tree.setSeq(area.getSeq());
		//tree.setChecked(area.getCheckd() > 0 ? true : false);
		return tree;
	}

	@Override
	public boolean verifyUniquely(Long id, String name, Long facId) {
		return agencyAreaMapper.verifyUniquely(id, name, facId) > 0 ? false : true;
	}

	@Override
	public List<Tree> findListByUser(Long facId, Long userId) {
		List<AgencyAreaVo> areaList = agencyAreaMapper.selectListByUser(facId, userId);
		
		Map<Long, List<Tree>> map = new HashMap<Long, List<Tree>>();
		List<Tree> valueList = null;
		Tree tree = null;

		for (int i = 0; i < areaList.size(); i++) {
			tree = convert(areaList.get(i));
			//从已有容器查找是否存在同级元素的集合
			if(map.get(tree.getPid()) == null) valueList = new ArrayList<Tree>();
			else valueList = map.get(tree.getPid());
			//根据当前节点查找下级节点集合是否存在，有则纳入封装体系
			if(map.get(tree.getId()) != null)
				tree.setChildren(map.get(tree.getId()));
			
			valueList.add(tree);
			map.put(tree.getPid(), valueList);
		}		
		
		return map.get(0L);
	}
	
	@Override
	public List<Tree> findTreeList(Long facId) {
		List<AgencyAreaVo> areaList = agencyAreaMapper.selectTreeList(facId);
		
		Map<Long, List<Tree>> map = new HashMap<Long, List<Tree>>();
		List<Tree> valueList = null;
		Tree tree = null;
		
		for (int i = 0; i < areaList.size(); i++) {
			tree = convert(areaList.get(i));
			//从已有容器查找是否存在同级元素的集合
			if(map.get(tree.getPid()) == null) valueList = new ArrayList<Tree>();
			else valueList = map.get(tree.getPid());
			//根据当前节点查找下级节点集合是否存在，有则纳入封装体系
			if(map.get(tree.getId()) != null)
				tree.setChildren(map.get(tree.getId()));
			
			valueList.add(tree);
			map.put(tree.getPid(), valueList);
		}		
		
		return map.get(0L);
	}
	
	
	@Override
	public List<Tree> findListByNews(Long facId, String filterArea) {
		List<AgencyAreaVo> areaList = agencyAreaMapper.selectListByNews(facId, filterArea);
		
		Map<Long, List<Tree>> map = new HashMap<Long, List<Tree>>();
		List<Tree> valueList = null;
		Tree tree = null;

		for (int i = 0; i < areaList.size(); i++) {
			tree = convert(areaList.get(i));
			//从已有容器查找是否存在同级元素的集合
			if(map.get(tree.getPid()) == null) valueList = new ArrayList<Tree>();
			else valueList = map.get(tree.getPid());
			//根据当前节点查找下级节点集合是否存在，有则纳入封装体系
			if(map.get(tree.getId()) != null)
				tree.setChildren(map.get(tree.getId()));
			
			valueList.add(tree);
			map.put(tree.getPid(), valueList);
		}		
		
		return map.get(0L);
	}
	
	
	@Override
	@Transactional
	public boolean updateUserAreas(Long userId, String areaIds) {
		List<Long> list = agencyAreaMapper.selectByUserId(userId);
		Long[] deletes = changeElements(LongUtils.convert(areaIds.split(",")), list.toArray(new Long[list.size()]));
		Long[] adds = changeElements(list.toArray(new Long[list.size()]),LongUtils.convert(areaIds.split(",")));
		int count = 0;
		if(deletes.length!=0){
			count = agencyAreaMapper.deleteSpecifiedUserArea(userId, deletes);
		}
		if(adds.length!=0){
			count += agencyAreaMapper.batchInsert(userId, adds);
		}
		return count >= 0 ? true : false;
	}

	/**
	 * Description:新旧关联比较--新在前返回删除  旧在前返回新增
	 * 
	 * @param news
	 * @param olds
	 * @return Long[]
	 * @author shaoqiping
	 * @date 2017年8月11日上午8:52:31
	 */
	public Long[] changeElements(Long[] news, Long[] olds) {
		List<Long> list= new ArrayList<Long>();
		for (Long i : olds) {
			int temp=0;
			for (Long j : news) {
				if(i==j){
					break;
				}
				temp++;
			}
			if(temp==news.length){
				list.add(i);
			}
		}
		return list.toArray(new Long[list.size()]);
	}

	/**
	 * 查询区域ID
	 */
	@Override
	public Long selectId(String str, Long facId) {
		
		return agencyAreaMapper.selectId(str, facId);
	}

	

	
}
